<template>
	<view style="overflow: hidden;">
		<!-- #ifndef MP-WEIXIN -->
		<navigationStyle />
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
		<navigationbar navtextColor="#fff" centerText="登录" :navigator="true" @emitNavigator="emitNavigator" />
		<!-- #endif -->
		<view class="login_img">
			<image src="http://106.14.56.171:15016/images/Smallicons/redLogin.png" mode=""></image>
		</view>
		<view class="login_btn">

			<!-- #ifdef APP-PLUS -->
			<view class="local_btn" @click="fastLogin">
				<button class="local_btn"><text>本机号码一键登录</text></button>
				<!-- #endif -->


				<!-- #ifdef MP-WEIXIN || H5 -->
				<view class="local_btn">
					<button class="local_btn" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber"><text>微信手机号一键登录</text></button>
					<!-- #endif -->
					<view class="abcsdhh" @click="closeChick" v-if="shareAuto"></view>
				</view>
				<view @click="goLocal" class="other_btn"><text>使用其他手机号登录</text></view>
			</view>
			<view class="fast_login">
				<view class="border_login">
					<view class="fast_border"></view>
					<text>快捷方式登录</text>
					<view class="fast_border"></view>
				</view>
				<view class="wxIosLoin">
					<button class="fast_wx" @click="wxLogin">
						<!-- 微信LOG -->
						<img src="http://106.14.56.171:15016/images/blank/wxLogin.png" />
					</button>
					
					<!-- #ifdef APP-PLUS  -->
					<!-- 苹果login登录 -->
					<button class="fast_wx" @click="appleLog" v-if="source==2">
						<img src="http://106.14.56.171:15016/images/blank/losLogin.png" />
					</button>
					<!-- #endif -->
				</view>
			</view>

			<view class="footer">
				<checkbox style="transform: scale(0.8)" :checked="checkValue" @click="check" class="round red">
				</checkbox>
				<view class="footer_text" @click="userAgreement">
					我已阅读并同意
					<text>《易乓乒用户协议和隐私协议》</text>
				</view>
			</view>
			<!-- 弹出框 -->
			<uni-popup ref="popup">
				<view class="model-wraper">
					<view class="modal-title">提醒</view>
					<view class="modal-body">您当前登录的微信并未绑定ePumping账户，请使用手机号登录或注册并绑定微信号后再使用微信登录功能</view>
					<view>
						<view class="btn cancel" @click="handleCancel">确认</view>
					</view>
				</view>
			</uni-popup>
			<Loading :loadingShow="loading"></Loading>
		</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		baseMethod
	} from '@/config/method.js'
	import Loading from '@/components/loading/loading.vue'
	// #ifndef MP-WEIXIN
	import navigationbar from '@/components/systemtabBar/navigationbar.vue'
	import navigationStyle from '@/components/systemtabBar/navigationStyle.vue'
	// #endif
	export default {
		data() {
			return {
				wxPhoneId: '', //微信小程序Id
				phoneNew: '',
				androidIos: '', //App:1:安卓ID,2:苹果ID
				push_clientid: '',
				shareAuto: true,
				checkValue: false,
				loading: false, // 加载中
			};
		},
		components: {
			Loading,
			// #ifndef MP-WEIXIN
			navigationbar,
			navigationStyle,
			// #endif

		},
		//#ifdef APP-PLUS
		// 应用App,本机一键登录
		onLoad() {
			this.fastLogin() //应用App,本机一键登录
		},
		// #endif
		computed: {
			...mapState(['userInfo'])
		},
		onLoad() {
			this.androidIos = getApp().globalData.androidIos
			this.source = getApp().globalData.source
		},
		methods: {
			...mapMutations(['setUserInfo']),
			appleLog() {
				if (!this.checkValue) {
					uni.showToast({
						title: '请勾选协议',
						icon: 'none'
					});
					return;
				}
				let _that = this
				uni.login({
					provider: 'apple',
					success: function(loginRes) {
						// 登录成功  
						uni.getUserInfo({
							provider: 'apple',
							success(res) {
								// 获取用户信息成功  
								console.log(res, '苹果信息成功')
								if (res.errMsg == 'getUserInfo:ok') {
									_that.loginCheck(res.userInfo.openId, '', 6, '')
								}
							}
						})
					},
					fail: function(err) {
						_that.loading = false
						console.log(err)
					}
				});
			},

			//#ifdef APP-PLUS
			// 应用App,本机一键登录
			fastLogin() {
				if (!this.checkValue) {
					uni.showToast({
						title: '请勾选协议',
						icon: 'none'
					});
					return;
				}
				var _that = this
				uni.login({
					provider: 'univerify',
					univerifyStyle: { // 自定义登录框样式
						//参考`univerifyStyle 数据结构`
						"fullScreen": true, // 是否全屏显示，默认值： false
					},
					success(res) { // 登录成功
						_that.loading = true
						console.log(res.authResult); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
						// 在得到access_token后，通过callfunction调用云函数
						uniCloud.callFunction({
							name: 'getPhoneNumber', // 你的云函数名称
							data: {
								'access_token': res.authResult
									.access_token, // 客户端一键登录接口返回的access_token
								'openid': res.authResult.openid // 客户端一键登录接口返回的openid
							}
						}).then(res => {
							// console.log('res陈征186', res);
							let phoneNumber = res.result.data.phoneNumber; //手机号
							let oneCode = res.result.data.code;
							_that.phoneNew = res.result.data.phoneNumber;
							if (res.result.message == '获取手机号成功') {
								if (oneCode == 0) {
									_that.loginCheck(phoneNumber, '', 5)
								} else {
									uni.showToast({
										title: '手机号登录异常，请尝试其他形式登录',
										icon: 'none'
									})
								}
							}
						}).catch(err => {
							_that.loading = false
							console.log(err, '-=========处理错误');
							// 处理错误
						})
					},
					fail(res) {
						_that.loading = false
						// 登录失败
						console.log('登录失败res', res);
						if (res.errCode == 30006) {
							uni.showToast({
								title: '一键登录失败,请尝试其他方式登录',
								icon: 'none'
							});
						} else if (res.errCode == 30005 || res.errCode == 0 || res.errMsg ==
							"login:fail provider not find") {
							uni.showToast({
								title: '请检测是否有手机号或者网络开启',
								icon: 'none'
							});
						}
					},
					// 接口调用结束的回调函数（调用成功、失败都会执行）
					complete() {
						uni.closeAuthView(); //关闭一键登录页面
					}
				})
			},
			// #endif
			//#ifdef MP-WEIXIN 
			getPhoneNumber(e) {
				console.log('获取微信信息', e);
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					uni.login({
						provider: 'weixin',
						success: res => {
							console.log(res, 123155555555);
							if (res.errMsg == 'login:ok') {
								this.loginCheck(e.detail.code, '', 3);
								// console.log('微信登录xin', e.detail.code, 3, wxPhoneId);
							} else {
								uni.showToast({
									title: '微信登录异常，请尝试其他形式登录',
									icon: 'none'
								});
							}
						}
					});
				}
			},
			// #endif
			// #ifdef MP-WEIXIN 
			wxLogin() {
				if (!this.checkValue) {
					uni.showToast({
						title: '请勾选协议',
						icon: 'none'
					});
					return;
				}
				var _that = this
				uni.getUserProfile({
					desc: '登录后可同步数据',
					lang: 'zh_CN',
					success: res_info => {
						_that.loading = true
						uni.login({
							provider: 'weixin',
							success: res => {
								console.log('微信', res)
								if (res.errMsg == 'login:ok') {
									_that.loginCheck(res.code, '', 2,
										res_info.userInfo.avatarUrl);
								} else {
									uni.showToast({
										title: '微信登录异常，请尝试其他形式登录',
										icon: 'none'
									});
									_that.loading = false
								}
							},
							fail: function() {
								_that.loading = false
							}
						});
					},
				});
			},
			// #endif
			// #ifdef APP-PLUS 
			wxLogin() {
				if (!this.checkValue) {
					uni.showToast({
						title: '请勾选协议',
						icon: 'none'
					});
					return;
				}
				var _that = this;
				_that.loading = true
				uni.login({
					provider: 'weixin',
					//onlyAuthorize: true, //非常重要，如果不加获取不到code
					success: function(res) {
						// console.log('获取用户信息', res);
						if (res.errMsg == 'login:ok') {
							_that.loginCheck(res.authResult.unionid, '', 4);
						} else {
							uni.showToast({
								title: '微信登录异常，请尝试其他形式登录',
								icon: 'none'
							});
							_that.loading = false
						}
						// 获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: function(res) {
								console.log(JSON.stringify(res.userInfo));
							}
						});
					},
					fail: function() {
						_that.loading = false
					}
				});
			},
			//非常重要，如果不加，App会报错 "toJSON"
			toJSON() {
				return this
			},
			// #endif
			loginCheck(code, phoneCode, loginType, avatarUrl) {
				// console.log('微信小程序', code, phoneCode, loginType, avatarUrl);
				let data = {
					appId: this.androidIos,
					// #ifdef APP-PLUS || H5
					phone: code,
					code: code,
					loginType: loginType,
					// #endif

					// #ifdef MP-WEIXIN
					source: this.source,
					phoneCode: code, //小程序本机登录
					code: code, //小程序快捷方式
					loginType: loginType,
					// #endif
				};
				console.log('getCid征', data);
				var _that = this
				this.$httpNew.post('authApi/auth/GetAppAuthCode', data).then(res => {
					console.log('---------------------陈征Token', res);
					this.loading = true
					if (res.accessToken) {
						uni.setStorageSync('accessToken', res.accessToken);
						uni.setStorageSync('refreshToken', res.refreshToken);
						this.$httpNew
							.post('authApi/auth/GetUserInfo', {
								appId: this.androidIos
							}).then(resUser => {
								console.log('resUser新的用户信息', resUser);
								_that.loading = false
								_that.setUserInfo(resUser);
								uni.switchTab({
									url: './../index/index'
								});
							}).catch(err => {
								_that.loading = false
							})
					} else {
						// #ifdef MP-WEIXIN
						uni.navigateTo({
							url: './information?phone=' + res.phone
						})
						// #endif
						_that.loading = false
					}
				}).catch(err => {
					console.log(err.errMsg.slice(1, 6), '苹果222222');
					let mistake = err.errMsg.slice(1, 6)
					if (mistake == 'A0021') {
						uni.showToast({
							title: 'Apple ID 未绑定',
							icon: 'none'
						});
						return;
					}

					_that.loading = false
					// #ifndef MP-WEIXIN
					console.log(err, err.statusCode, _that.phoneNew, '新的环境App');
					if (mistake == 'A0010') {
						uni.navigateTo({
							url: './information?phone=' + _that.phoneNew
						})
						return;
					}
					// #endif
				})
			},

			// 手机验证码登录页面
			goLocal() {
				uni.navigateTo({
					url: './mobile_login'
				});
			},

			handleCancel() {
				this.$refs.popup.close();
			},

			// 偷懒方法,勾选协议
			closeChick() {
				if (!this.checkValue) {
					uni.showToast({
						title: '请勾选协议',
						icon: 'none'
					});
					return;
				}
			},
			check() {
				this.checkValue = !this.checkValue;
				this.shareAuto = false;
			},
			// 微信修改图片
			wxFileImaUser(file, token, userInfo) {
				let baseUrl = `${baseMethod()}api/user/uploadUserHead`
				console.log(baseUrl, file, token, userInfo)
				var _that = this
				uni.uploadFile({
					url: baseUrl,
					filePath: file,
					name: 'file',
					formData: {
						'count': '1'
					},
					header: {
						'Authorization': 'Bearer ' + token
					},
					success: function(uploadFileRes) {
						console.log(uploadFileRes)
						if (uploadFileRes.statusCode == 200) {
							let data = JSON.parse(uploadFileRes.data)
							console.log(data)
							userInfo.headPortrait = data.data ? data.data : userInfo.headPortrait
							_that.setUserInfo(userInfo);
							uni.switchTab({
								url: './../index/index'
							})
							_that.loading = false
						}
					},
					fail: function(errFile) {
						_that.setUserInfo(userInfo);
						uni.switchTab({
							url: './../index/index'
						});
						_that.loading = false
					}
				})
			},

			// 点击打开用户协议
			userAgreement() {
				uni.navigateTo({
					url: './userAgreement'
				});
			},

			onBackPress(options) {
				// 触发返回就会调用此方法，这里实现的是禁用物理返回，顶部导航栏的自定义返回 uni.navigateBack 仍可使用
				if (options.from == 'backbutton') {
					return true;
				} else if (options.from == 'navigateBack') {
					return false;
				}
			},
			// 自定义返回
			emitNavigator() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	};
</script>

<style lang="less" scope>
	page {
		background-color: #fffFFF;
	}

	.model-wraper {
		width: 600rpx;
		background-color: #fff;
		box-shadow: #dcdcdc 0px 0px 20rpx;
	}

	.modal-title {
		height: 90rpx;
		line-height: 90rpx;
		width: 100%;
		text-align: center;
		font-size: 32rpx;
		color: #666;
	}

	.modal-body {
		padding: 30rpx 30rpx 80rpx 30rpx;
	}

	.btn {
		width: 300rpx;
		height: 90rpx;
		text-align: center;
		line-height: 90rpx;
		font-size: 32rpx;
		background-color: #fff;
		float: left;
		border-radius: 0rpx;
	}

	.btn.cancel {
		width: 100%;
		border-right: 1rpx solid #dcdcdc;
	}

	button::after {
		border: none;
		background-color: none;
	}

	.login_img {
		width: 100%;
		height: 500rpx;
		margin-top: 150rpx;
		// background-color: aqua;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
	}

	.login_img image {
		width: 200rpx;
		height: 200rpx;
	}

	.login_img text {
		font-size: 34rpx;
		font-weight: 400;
		color: #333;
	}

	.login_btn {
		width: 100%;
		height: 280rpx;
		padding: 0 40rpx;
		text-align: center;
	}

	.login_btn .local_btn {
		line-height: 90rpx;
		color: #fff;
		font-size: 36rpx;
		margin-bottom: 50rpx;
		width: 90%;
		height: 90rpx;
		background-color: #c6001b;
		border-radius: 50rpx;
	}

	// 偷懒方法,勾选协议
	.abcsdhh {
		position: relative;
		top: -138rpx;
		margin: auto;
		width: 100%;
		height: 90rpx;
		// background-color: #04be02;
		border-radius: 50rpx;
		z-index: 9999999;
	}

	.login_btn .other_btn {
		border: #ccc 1rpx solid;
		line-height: 90rpx;
		color: #333;
		font-size: 36rpx;
		width: 90%;
		height: 90rpx;
		background-color: #fff;
		border-radius: 50rpx;
	}

	.fast_login .border_login {
		display: flex;
		justify-content: center;
		margin-top: 30rpx;
	}

	.fast_login text {
		font-size: 29rpx;
		color: #989898;
		margin-left: 40rpx;
		margin-right: 40rpx;
	}

	.fast_login .fast_border {
		width: 140rpx;
		height: 20rpx;
		border-bottom: solid 3rpx #c6001b;
	}

	.fast_login .fast_wx {
		text-align: center;
		// margin-top: 50rpx;
		background-color: #FFFFFF;
		// background-color: aqua;
	}

	.fast_login .fast_wx img {
		width: 100rpx;
		height: 100rpx;
	}

	.wxIosLoin {
		margin: auto;
		margin-top: 20px;
		width: 200px;
		// background-color: aqua;
		display: flex;
	}

	.footer {
		position: absolute;
		bottom: 60rpx;
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: center;
		color: #333;
		font-size: 20rpx;
		line-height: 30rpx;
		font-weight: bold;
		margin-left: 15%;
	}

	.footer img {
		margin-top: 5rpx;
		width: 22rpx;
		height: 22rpx;
	}

	.footer_text {
		margin-left: 15rpx;
		width: 90%;
	}

	.footer_text text {
		color: #c6001b;
	}
</style>